package com.project.quiktask.datastore;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Vector;
import com.project.quiktask.Task;
import com.project.quiktask.util.Variable;

/**
 * A service class that handles file storage
 * @author PHAM MINH VIET
 */
public class FileStorer {
	private BufferedWriter writer;
	private FileWriter fStream;
	
	/**
	 * This method writes a list of tasks into the file associated with fileName
	 * @param eventsToBeStored - List of Tasks that will be written into a file
	 * @throws IOException - occurs when access to file is failed
	 */
	/*public void store(Vector<Task> tasksToBeStored) throws IOException {
		this.fStream= new FileWriter(Variable.fileName);
		this.writer= new BufferedWriter(fStream);
		for (Task task : tasksToBeStored) {
			String stringToWrite = FileConverter.taskObjectToString(task);
			writer.write(stringToWrite);
		}
		this.close();
	}*/
	
	public void storeTask(Task task) throws IOException{
		this.fStream= new FileWriter(Variable.STORAGE_FILE_NAME,true);
		this.writer= new BufferedWriter(fStream);
		String taskInString=FileConverter.taskObjectToString(task);
		writer.write(taskInString);
		this.close();
	}
	
	public void storeManyTask(Vector<Task> tasksToBeStored) throws IOException{
		this.fStream= new FileWriter(Variable.STORAGE_FILE_NAME,false);
		this.writer= new BufferedWriter(fStream);
		for(Task task:tasksToBeStored){
		String taskInString=FileConverter.taskObjectToString(task);
		writer.write(taskInString);
		}
		this.close();
	}
	
	public void storeTask(Task task,String fileName) throws IOException{
		this.fStream= new FileWriter(fileName,true);
		this.writer= new BufferedWriter(fStream);
		String taskInString=FileConverter.taskObjectToString(task);
		writer.write(taskInString);
		this.close();
	}
	
	public void storeManyTask(Vector<Task> tasksToBeStored,String fileName) throws IOException{
		this.fStream= new FileWriter(fileName,false);
		this.writer= new BufferedWriter(fStream);
		for(Task task:tasksToBeStored){
		String taskInString=FileConverter.taskObjectToString(task);
		writer.write(taskInString);
		}
		this.close();
	}
	
	
	/**
	 * Closes the stream
	 * @throws IOException
	 */
	public void close() throws IOException {
		this.writer.close();
	}
}
